package com.itheima.reggie.controller;


import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.service.AddressService;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @GetMapping("list")
    public ResultInfo findAddress() {

        List<Address> addresses = addressService.findAll();

        return ResultInfo.success(addresses);
    }


    @PostMapping
    public ResultInfo add(@RequestBody Address address) {

        addressService.add(address);

        return ResultInfo.success(null);
    }


    @GetMapping("{id}")
    public ResultInfo FindAddressById(@PathVariable Long id) {
        Address byId = addressService.findById(id);
        return ResultInfo.success(byId);
    }

    @PutMapping
    public ResultInfo updateAddress(@RequestBody Address address) {

        addressService.updateAddress(address);

        return ResultInfo.success(null);
    }

    @DeleteMapping
    public ResultInfo deleteAddress(@RequestParam List<Long> ids) {
        addressService.deleteByIds(ids);
        return ResultInfo.success(null);
    }

    @PutMapping("default")
    public ResultInfo setDefault(@RequestBody Map<String, Long> map) {
        Long id = map.get("id");

        addressService.setAddressDefault(id);
        return ResultInfo.success(null);
    }

    @GetMapping("default")
    public ResultInfo findDefaultAddress() {
        Address address = addressService.findDefaultADdress();

        //要保证程序的健壮性
        if (address == null) {
            throw new CustomException("没有默认地址");
        } else {

            return ResultInfo.success(address);
        }

    }
}
